package tencent

import (
	"fmt"
	"github.com/spf13/viper"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	sms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111"
)

func (r *Tencent) NewSms(slugs ...string) *Sms {
	slug := "default"
	if len(slugs) > 0 {
		slug = slugs[0]
	}
	config := viper.GetStringMapString(fmt.Sprintf("org.tencent.sms.%s", slug))

	return &Sms{
		org:      r,
		endpoint: "sms.tencentcloudapi.com",
		appId:    config["appId"],
		sign:     config["sign"],
	}
}

type Sms struct {
	org      *Tencent
	endpoint string
	appId    string
	sign     string
}

// ### 模型

type SmsSendReq struct {
	PhoneNumber        string
	TemplateId         string    `json:"template_id"`
	TemplateParameters []*string `json:"template_parameters,omitempty"`
}

// ### 方法

func (r *Sms) Send(req *SmsSendReq) (*sms.SendSmsResponse, error) {
	credential := common.NewCredential(r.org.secretId, r.org.secretKey)
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = r.endpoint
	client, _ := sms.NewClient(credential, r.org.region, cpf)

	request := sms.NewSendSmsRequest()
	request.SmsSdkAppId = &r.appId
	request.SignName = &r.sign
	request.TemplateId = &req.TemplateId
	request.PhoneNumberSet = []*string{&req.PhoneNumber}
	request.TemplateParamSet = req.TemplateParameters

	response, err := client.SendSms(request)
	if err != nil {
		fmt.Printf("An error occurred: %v", err)
	} else {
		fmt.Printf("SendSms response: %s", response.ToJsonString())
	}

	return response, err
}
